package com.luckynote.common.base.serialize;

import com.luckynote.common.base.util.BeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 * <pre>
 * *********************************************
 * Copyright LUCKY-NOTE.
 * All rights reserved.
 * ****************************************************
 *  Version       Date         Author            Desc
 *    v1.0       2019/6/29      bingo
 * ****************************************************
 * </pre>
 */
public class JasonSerializerUtil {

    private static final Logger logger = LoggerFactory.getLogger(JasonSerializerUtil.class);

    /**
     * 序列化对象，失败或异常返回null
     * @param source 待序列化的目标对象
     * @return 已序列化的Json
     */
    public static byte[] serialize(Object source) {
        if ( source == null )
            return null;
        try {
            return BeanUtil.toJson(source).getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("对象序列化失败", e);
        }
        return null;
    }

    /**
     * 反序列化对象，失败或异常返回null
     * @param source 已序列化的Json
     * @param typeOfT 反序列化目标类
     * @param <T> 反序列化对象
     * @return 反序列化对象
     */
    public static <T> T deSerialize(byte[] source, Class<T> typeOfT) {
        if ( source == null || typeOfT == null )
            return null;

        try {
            String jsonString = new String(source,"UTF-8");
            return BeanUtil.fromJson(jsonString, typeOfT);
        } catch (UnsupportedEncodingException e) {
            logger.error("对象反序列化失败", e);
        }

        return null;
    }

}
